// DOM元素
const pickBtn = document.getElementById('pickBtn');
const resultBox = document.getElementById('result');
const nameList = document.getElementById('nameList');

// 变量
let isRolling = false;
let rollInterval = null;
let currentName = '';

// 从本地存储获取名单
function getNames() {
    const names = localStorage.getItem('names');
    return names ? JSON.parse(names) : [];
}

// 显示名单
function displayNames() {
    const names = getNames();
    nameList.innerHTML = '';
    
    if (names.length === 0) {
        nameList.innerHTML = '<li>暂无人员，请先添加</li>';
        return;
    }
    
    names.forEach((name, index) => {
        const li = document.createElement('li');
        li.textContent = name;
        nameList.appendChild(li);
    });
}

// 随机点名
function toggleRandomName() {
    const names = getNames();
    
    if (names.length === 0) {
        resultBox.innerHTML = '<p>暂无人员，请先添加</p>';
        return;
    }
    
    if (!isRolling) {
        // 开始随机选择
        isRolling = true;
        pickBtn.textContent = '停止';
        pickBtn.classList.add('danger-btn');
        pickBtn.classList.remove('primary-btn');
        resultBox.classList.remove('highlight');
        
        // 开始滚动显示随机名字
        rollInterval = setInterval(() => {
            const randomIndex = Math.floor(Math.random() * names.length);
            currentName = names[randomIndex];
            resultBox.innerHTML = `<p>${currentName}</p>`;
        }, 100);
    } else {
        // 停止随机选择
        isRolling = false;
        clearInterval(rollInterval);
        
        // 短暂延迟后跳转到祝贺页面
        setTimeout(() => {
            // 跳转到祝贺页面，并传递选中的名字
            window.location.href = `congratulation.html?name=${encodeURIComponent(currentName)}`;
        }, 500);
    }
}

// 事件监听
pickBtn.addEventListener('click', toggleRandomName);

// 页面加载时显示名单
window.addEventListener('load', displayNames); 